package org.iwidget.desktop.core;
import org.iwidget.desktop.model.WidgetElement;
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
/**
 *
 * @author Muhammad Hakim A
 */


public class TransparentFrame extends JDialog
{

    public TransparentFrame(WidgetElement widget)
    {
        formOpen = null;
        doTrans = false;
        enableRepaint = true;
        intrans = false;
        this.widget = widget;
        setUndecorated(true);
    }

    public JDialog getFormOpen()
    {
        return formOpen;
    }

    public void setFormOpen(JDialog dialog)
    {
        formOpen = dialog;
    }

    public void forceDoTrans()
    {
        doTrans = true;
    }

    public void initComponents()
    {
        label = new JLabel();
        label.setSize(getSize().width, getSize().height);
        label.setLocation(0, 0);
        label.setDoubleBuffered(true);
        getContentPane().add(label);
    }

    public void maketrans()
    {
        if(getWidth() > 0 && getHeight() > 0)
            maketrans(new Rectangle(getX(), getY(), getWidth(), getHeight()));
    }

    public void maketrans(Rectangle rect)
    {
        if(isVisible() && !intrans)
        {
            intrans = true;
            setVisible(false);
            if(robot == null)
                try
                {
                    robot = new Robot();
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }
            robot.delay(130);
            bi = robot.createScreenCapture(rect);
            label.setIcon(new ImageIcon(bi));
            setVisible(true);
            intrans = false;
        }
    }

    public void enableRepaint(boolean enableRepaint)
    {
        this.enableRepaint = enableRepaint;
    }

    @Override
    public void paint(Graphics g)
    {
        if(enableRepaint)
        {
            Rectangle r = g.getClipBounds();
            if(r.x > 0 && r.y > 0 && r.x + r.width < getWidth() && r.y + r.height < getHeight())
            {
                try
                {
                    super.paint(g);
                }
                catch(Exception e) { }
                return;
            }
            if(r.x == 0 && r.y == 0 && (r.width < getWidth() || r.height < getHeight()))
                maketrans();
            if(r.x != 0 || r.y != 0 || r.x + r.width < getWidth() || r.y + r.height < getHeight())
                maketrans();
            super.paint(g);
        }
    }

    private static final long serialVersionUID = 0x3539303733323630L;
    private WidgetElement widget;
    private Robot robot;
    private JLabel label;
    private JDialog formOpen;
    private boolean doTrans;
    private boolean enableRepaint;
    private BufferedImage bi;
    boolean intrans;
}